﻿using System;
using System.ComponentModel;
using System.Collections.Specialized;
using System.Drawing;
using System.Runtime.InteropServices;
using PSGQuickTimeTracker.Properties;
using System.Windows.Forms;
using MouseKeyboardActivityMonitor;
using MouseKeyboardActivityMonitor.WinApi;


namespace PSGQuickTimeTracker
{	
	public partial class MainWindow : Form
	{
		private bool   _shouldClose;
		private bool   _hasChanged;
		private bool   _enableSubmit; 
		private string _curTaskType = "QuickTurn";
		
		private DataModel.QTTasks TaskList = new DataModel.QTTasks();
		private readonly KeyboardHookListener m_KeyboardHookManager;

        private DataModel.MyTheme theme = new DataModel.MyTheme();

	

		/// <summary>
		/// Initialize a new window instance.
		/// </summary>
		public MainWindow()
		{
			InitializeComponent();

			m_KeyboardHookManager = new KeyboardHookListener(new GlobalHooker());
			m_KeyboardHookManager.Enabled = true;
			m_KeyboardHookManager.KeyDown += Hotkey_Handler;
			
			lblVersion.Text = Application.ProductVersion;

			 // Categories
			foreach (var item in Settings.Default.Categories) {
				TCategory.Items.Add(item);
			}

			// Other Values
			LoadSettings();

            // Theme
            ApplyTheme();

			// Set defaults
			ResetFields();
		}



        private void ApplyTheme()
        {

            #region Main Labels
            MainSplit.Panel2.BackColor = theme.MainBack;
            lblCategory.ForeColor = theme.LabelFore;
            lblCategory.Font = theme.MainFont;
            lblUser.ForeColor = theme.LabelFore;
            lblUser.Font = theme.MainFont;
            lblDate.ForeColor = theme.LabelFore;
            lblDate.Font = theme.MainFont;
            lblDuration.ForeColor = theme.LabelFore;
            lblDuration.Font = theme.MainFont;
            lblDesc.ForeColor = theme.LabelFore;
            lblDesc.Font = theme.MainFont;
            #endregion

            #region Input Controls
            TDate.Font = theme.MainFont;
            TUser.BackColor = theme.ControlBack;
            TUser.ForeColor = theme.ControlFore;
            TUser.Font = theme.MainFont;
            TCategory.BackColor = theme.ControlBack;
            TCategory.ForeColor = theme.ControlFore;
            TCategory.Font = theme.MainFont;
            TDuration.BackColor = theme.ControlBack;
            TDuration.ForeColor = theme.ControlFore;
            TDuration.Font = theme.MainFont;
            TDescription.BackColor = theme.ControlBack;
            TDescription.ForeColor = theme.ControlFore;
            TDescription.Font = theme.MainFont; 
            #endregion

            #region Tabs
            ApplyTabTheme();
            #endregion

            #region Title Bar
            MainSplit.Panel1.BackColor = theme.TitleBar;
            btnHKSettings.Font = theme.LinkBtnFont; 
            #endregion
        }


        private void ApplyTabTheme()
        {
            var actTab = this.Controls["tab" + _curTaskType] as Button;
            var inActTab = (Button)this.Controls["tab" + (_curTaskType == "QuickTurn" ? "EMail" : "QuickTurn")];

            string verb = _curTaskType == "QuickTurn" ? "Active" : "Inactive";

            tabQuickTurn.BackColor = (Color)Settings.Default["Theme_Tab" + verb + "Back"];
            tabQuickTurn.ForeColor = (Color)Settings.Default["Theme_Tab" + verb + "Fore"];
            tabQuickTurn.FlatAppearance.BorderColor = (Color)Settings.Default["Theme_Tab" + verb + "Border"];

            verb = verb == "Active" ? "Inactive" : "Active";

            tabEMail.BackColor = (Color)Settings.Default["Theme_Tab" + verb + "Back"];
            tabEMail.ForeColor = (Color)Settings.Default["Theme_Tab" + verb + "Fore"];
            tabEMail.FlatAppearance.BorderColor = (Color)Settings.Default["Theme_Tab" + verb + "Border"];
        }
			


		private void Open()
		{
			Show();
		}



		private void btnClose_Click(object sender, EventArgs e)
		{
			Close();
		}

				
		protected override void OnClosing(CancelEventArgs e)
		{
			if (_hasChanged)
			{
				if (MessageBox.Show(this, Settings.Default.Prompt_LoseChanges, Settings.Default.Prompt_Title,
						MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes)
				{
					e.Cancel = true;
					return;
				}
			}
			if (!_shouldClose)
			{
				e.Cancel = true;
				Hide();
				ResetFields();
			}
		}
		

		#region Window Drag Handler

		[DllImportAttribute("user32.dll")]
		public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
		[DllImportAttribute("user32.dll")]
		public static extern bool ReleaseCapture();


		/// <summary>
		/// Handle mousedown even for window to allow dragging GUI without title bar.
		/// </summary>
		private void MainSplit_Panel1_MouseDown(object sender, MouseEventArgs e)
		{
			if (e.Button == System.Windows.Forms.MouseButtons.Left)
			{
				ReleaseCapture();
				SendMessage(Handle, 0xA1, 0X2, 0);
			}

		}
		#endregion

		

		#region Tab Click Handlers

		private void tabEMail_Click(object sender, EventArgs e)
		{
			if (_curTaskType != "EMail")
			{
				// Set the current task context
				_curTaskType = "EMail";
				
				// Set the dynamic control values
				LoadSettings();

                ApplyTabTheme();
			}
		}


		private void tabQuickTurn_Click(object sender, EventArgs e)
		{
			if (_curTaskType != "QuickTurn")
			{    
				// Set the current task context
				_curTaskType = "QuickTurn";               
				
				// Load dynamic control values
				LoadSettings();

				ApplyTabTheme();
			}
		}
		#endregion


		
		private void LoadSettings()
		{
			// Load Durations
			TDuration.Items.Clear();
			foreach (var item in (StringCollection)Settings.Default["Durations_" + _curTaskType])
			{
				TDuration.Items.Add(item);
			}

			// Set Description Max
			TDescription.MaxLength = (int)Settings.Default["MaxDesc_" + _curTaskType];
			string remCount = (TDescription.MaxLength - TDescription.TextLength).ToString();
			lblDesc.Text = "Description  (" + remCount + " chars remaining)";
		}



		/// <summary>
		/// Event handler for double-clicking the tray icon.
		/// </summary>
		private void TrayIcon_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			if (e.Button == MouseButtons.Left)
			{
				Open();
			}
		}

		
			   
		/// <summary>
		/// Tray menu click event handler
		/// </summary>
		private void TrayMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
		{
			switch (e.ClickedItem.Name.Replace("menuItem", ""))
			{
				case "Open":
					Show();
					break;

				case "Exit":
					_shouldClose = true;
					Close();
				    break;

				case "Hotkey":
					CustomizeHotkey();
					break;

				case "Update":
                case "CheckUpdate":
					if (PSGQuickTimeTracker.Update.CheckUpdate())					
						MessageBox.Show("An update is available!\n\nExit the application and restart is to get the latest version.");
					else
						MessageBox.Show("There is no update available.");
					break;
			}
		}
		


		private void CustomizeHotkey()
		{
			var newHK = new SetHotkey().ShowDialog(this);
			if (newHK == DialogResult.Yes)
				TrayIcon.ShowBalloonTip(1500, "PSG Quick Time Tracker", "Hotkey successfully changed!", ToolTipIcon.Info);
		}



		/// <summary>
		/// Called when any of the task fields change. 
		/// Validates & enables task submission.
		/// </summary>
		private void PropChange(object sender, EventArgs e)
		{
			// Update the remaining char count for description
			if (((Control)sender).Name == "TDescription")
			{   
								
				string remCount = (TDescription.MaxLength - TDescription.TextLength).ToString();
				lblDesc.Text = "Description  (" + remCount + " chars remaining)";
			}
			
			if (string.IsNullOrWhiteSpace(TDate.Text) || string.IsNullOrEmpty(TDate.Text)
				|| string.IsNullOrWhiteSpace(TUser.Text) || string.IsNullOrEmpty(TUser.Text)
				|| string.IsNullOrWhiteSpace(TCategory.Text) || string.IsNullOrEmpty(TCategory.Text)
				|| string.IsNullOrWhiteSpace(TDescription.Text) || string.IsNullOrEmpty(TDescription.Text)
				|| string.IsNullOrWhiteSpace(TDuration.Text) || string.IsNullOrEmpty(TDuration.Text))
			{
				_enableSubmit = false;
				btnSubmit.Enabled = false;
			}
			else
			{
				_enableSubmit = true;
				btnSubmit.Enabled = true;
			}
			_hasChanged = true;
		}



		/// <summary>
		/// Resets all task fields to their default values.
		/// </summary>
		void ResetFields()
		{
			TDate.Text = DateTime.Now.ToShortDateString();
			TUser.Text = Environment.UserName;
			TCategory.Text = string.Empty;
			TDuration.Text = string.Empty;
			TDescription.Text = string.Empty;
			tabQuickTurn_Click(this, EventArgs.Empty);

			_hasChanged = false;
			_enableSubmit = false;
			TCategory.Focus();
		}


		/// <summary>Submit Button Handler</summary>
		private void btnSubmit_Click(object sender, EventArgs e)
		{
			if (!_enableSubmit)
			{
				MessageBox.Show(this, Settings.Default.Prompt_IncompleteEntry, Settings.Default.Prompt_Title,
									MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				return;
			}
			else
			{
				TaskList.ReloadTasks();

				var tmpTask = new DataModel.QTTask(TUser.Text, TDate.Text, TCategory.Text,
						TDuration.Text, TDescription.Text, _curTaskType);

				TaskList.Add(tmpTask);
				TaskList.export();
				ResetFields();
				Close();
			}
		}



		private void Hotkey_Handler(object sender, KeyEventArgs e)
		{	
			//TrayIcon.ShowBalloonTip(1500, "PSG Quick Time Tracker", string.Format("Ctrl: {0}\nAlt: {1}\nShift: {2}", e.Control.ToString(), e.Alt.ToString(), e.Shift.ToString()),ToolTipIcon.Info);
			if (e.KeyCode.ToString() == Settings.Default.Hotkey_hkKey)
			{
				
				if (ModifierKeys.ToString() == Settings.Default.Hotkey_Mods)
					Show();
			}
		}



		private void btnSubmit_EnabledChanged(object sender, EventArgs e)
		{
			if (btnSubmit.Enabled == false)
			{
				btnSubmit.FlatAppearance.BorderColor = Color.LightGray;
				btnSubmit.ForeColor = Color.LightGray;
			}
			else
			{
				btnSubmit.FlatAppearance.BorderColor = Color.CornflowerBlue;
				btnSubmit.ForeColor = Color.CornflowerBlue;
			}
		}


		private void btnHKSettings_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			CustomizeHotkey();
        }
	}
}
